import { observable, action } from 'mobx';
import { WeaTools } from 'ecCom';
import moment from 'moment';
import * as knowledge from '../../apis/knowledge/knowledge';

let Base64 = ecCom.WeaTools.Base64;
export default class KnowledgeEditStore {
  constructor(props) {
  }
  @observable loading = false;
  @observable hasRight = false;
  @observable name = '';
  @observable remark = '';
  @observable datas = [];
  @observable knowledgetype='';
  @observable knowledgetypelist=[]
  @observable knowledgetypeOption=[];

  /**
   * 获取知识点详细信息
   */
  @action
  getKnowledgeDetail(params) {
    this.loading = true;
    knowledge.getKnowledgeDetail(params).then((data) => {
      if (data.status == 1) {
        this.name = data.name;
        this.remark = data.remark;
        this.hasRight = data.hasRight;
        this.datas = data.dataDetail;
        // this.knowledgetypeOption = this.getKnowledgeTypeOption(data.knowledgetypelist);
      }
      this.loading = false;
    });
  }

  /**
   * 保存知识点信息
   */
  @action
  saveKnowledge(params) {
    this.loading = true;
    let dataEncodeBefore = JSON.parse(params.datas);
    dataEncodeBefore && dataEncodeBefore.length > 0 && dataEncodeBefore.map((element, index) => {
      element.sqlstr = Base64.encode(encodeURIComponent(element.sqlstr));
    });
    params.datas = JSON.stringify(dataEncodeBefore);
    knowledge.operateKnowledge(params).then((data) => {
      if (data.status == 1) {
        let responseStatus = data.responseStatus || '';
        let knowledgeId = data.knowledgeId || '';
        if (params.doback && knowledgeId) {
            params.doback(knowledgeId);
        }
      }
      this.loading = false;
    });
  }

  @action
  getKnowledgeTypeOption(knowledgetypelist) {
    let optionArray = [];
    let knowledgeOption = {};
    knowledgeOption.key = '';
    knowledgeOption.showname = '';
    optionArray.push(knowledgeOption);
    for (let i = 0; i < knowledgetypelist.length; i++) {
      knowledgeOption = {};
      knowledgeOption.key = knowledgetypelist[i].id;
      knowledgeOption.showname = knowledgetypelist[i].name;
      optionArray.push(knowledgeOption);
    }
    return optionArray;
  }

  @action
  saveKnowledgeType(params) {
    this.loading = true;
    knowledge.saveKnowledgeType(params).then((data) => {
      if (data.status == 1) {
        this.knowledgetypelist = data.listType;
        this.knowledgetypeOption = this.getKnowledgeTypeOption(data.listType);
        if (params.doback) {
           params.doback();
        }
      }
      this.loading = false;
    });
  }

  @action
  setState = (params = {}) => {
    Object.keys(params).forEach((key) => {
      this[key] = params[key];
    });
    return this;
  }
  
}
